package com.kun.peng.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kun.peng.system.domain.Dict;
import com.kun.peng.system.domain.DictDetail;
import com.kun.peng.system.service.DictService;
import com.kun.peng.utils.*;
import com.kun.peng.mybatis.base.IBaseService;
import com.kun.peng.system.mapper.DictDetailMapper;
import com.kun.peng.system.service.DictDetailService;
import com.kun.peng.system.service.dto.DictDetailQueryCriteria;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created on 2021/12/14.
 *
 * @author xuebaopeng
 * Description
 */
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dict")
public class DictDetailServiceImpl extends IBaseService<DictDetailMapper, DictDetail> implements DictDetailService {
    private final RedisUtils redisUtils;
    private final DictService dictService;
    @Override
    public IPage<DictDetail> queryAll(DictDetailQueryCriteria criteria) {
        Page<DictDetail>  detailIPage=new Page();
        detailIPage.setCurrent(criteria.getPage());
        detailIPage.setSize(criteria.getSize());
        IPage<DictDetail> iPage= getBaseMapper().selectDictDetailByPage(detailIPage,criteria.getLabel(),criteria.getDictName());
        return iPage;
    }

    @Override
    public void create(DictDetail resources) {
        getBaseMapper().insert(resources);
        // 清理缓存
        delCaches(resources);
    }

    @Override
    public void updateDictDetail(DictDetail resources) {
        DictDetail dictDetail = findById(resources.getId()).orElseGet(DictDetail::new);
        ValidationUtil.isNull( dictDetail.getId(),"DictDetail","id",resources.getId());
        resources.setId(dictDetail.getId());
        save(resources);
        // 清理缓存
        delCaches(resources);
    }

    @Override
    public void delete(Long id) {
        DictDetail dictDetail =findById(id).orElseGet(DictDetail::new);
        // 清理缓存
        delCaches(dictDetail);
        getBaseMapper().deleteById(id);
    }
    public void delCaches(DictDetail dictDetail){
        Dict dict = dictService.findDictById(dictDetail.getDict().getId());
        redisUtils.del(CacheKey.DICT_NAME + dict.getName());
    }
}
